from __future__ import print_function
from flask import Flask, Response
from pyzbar import pyzbar
from picamera.array import PiRGBArray
from picamera import PiCamera
from datetime import datetime

import numpy as np
import cv2
import time
import json

from play import playQrDi
import config
import reboot

def qrread():
  with PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(640, 480))
    time.sleep(1)
    while True:
      ret = get_frame(camera, rawCapture)
      if ret:
        break
  reboot.shutdown()

# camera = PiCamera()
# camera.resolution = (640, 480)
# camera.framerate = 32
# rawCapture = PiRGBArray(camera, size=(640, 480))
# time.sleep(0.1)

# app = Flask(__name__)


# @app.route('/stream')
# def stream():
#     return Response(gen(),
#                     mimetype='multipart/x-mixed-replace; boundary=frame')

# def gen():
#     while True:
#         frame = get_frame()
#         yield (b'--frame\r\n'
#                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

def get_frame(camera, rawCapture):
    camera.capture(rawCapture, format="bgr", use_video_port=True)
    frame = rawCapture.array
    decoded_objs = process_frame(frame)
    # ret, jpeg = cv2.imencode('.jpg', frame)
    rawCapture.truncate(0)

    # return jpeg.tobytes()
    return len(decoded_objs) > 0
    
def process_frame(frame):
    decoded_objs = decode(frame)
    # draw_positions(frame, decoded_objs)
    return decoded_objs

def decode(frame):
    decoded_objs = pyzbar.decode(frame, scan_locations=True)
    for decoded_obj in decoded_objs:
        playQrDi()
        print(datetime.now().strftime('%H:%M:%S.%f'))
        print('Type: ', decoded_obj.type)
        print('Data: ', decoded_obj.data)
        do_config(decoded_obj.data)
        break
    
    return decoded_objs

def do_config(cfg):
    cfg = json.loads(cfg.decode('utf8'))
    if 'ssid' in cfg and cfg['ssid'] is not None:
        ssid = cfg['ssid']
        if 'psk' in cfg:
          psk = cfg['psk']
        else:
          psk = 'NONE'
        # wpa_config.connect_wireless_with_wpa(ssid, psk)
        print('ssid: %s' % ssid)
        print('psk: %s' % psk)
        config.add_ssid(ssid, psk)
    if 'wsUrl' in cfg and cfg['wsUrl'] is not None:
        wsUrl = cfg['wsUrl']
        print('wsUrl: %s' % wsUrl)
        config.set_env('wsUrl', wsUrl)
    if 'restUrl' in cfg and cfg['restUrl'] is not None:
        restUrl = cfg['restUrl']
        print('restUrl: %s' % restUrl)
        config.set_env('restUrl', restUrl)
    if 'id' in cfg and cfg['id'] is not None:
        id = cfg['id']
        print('id: %s' % id)
        config.set_env('id', id)
    if 'warningId' in cfg and cfg['warningId'] is not None:
        warningId = cfg['warningId']
        print('warningId: %s' % warningId)
        config.set_env('warningId', warningId)
    if 'supportAcceptId' in cfg and cfg['supportAcceptId'] is not None:
        supportAcceptId = cfg['supportAcceptId']
        print('supportAcceptId: %s' % supportAcceptId)
        config.set_env('supportAcceptId', supportAcceptId)
    if 'supportDenyId' in cfg and cfg['supportDenyId'] is not None:
        supportDenyId = cfg['supportDenyId']
        print('supportDenyId: %s' % supportDenyId)
        config.set_env('supportDenyId', supportDenyId)
    if 'reset' in cfg and cfg['reset'] is not None:
        reset = cfg['reset']
        print('reset: %s' % reset)
        config.set_env('reset', reset)

def draw_positions(frame, decoded_objs):
    for decoded_obj in decoded_objs:
        left, top, width, height = decoded_obj.rect
        frame = cv2.rectangle(frame,
                              (left, top),
                              (left + width, height + top),
                              (0, 255, 0), 2)


if __name__ == '__main__':
    # app.run(host="0.0.0.0", debug=False, threaded=True)
    # config = '''{
    #   "ssid": "zhongyi_Office",
    #   "psk": "123123one"
    # }'''
    qrread()
